using System;
using System.Threading;
using log4net;

namespace Sedna.Core.Messaging.InMemoryImpl
{
	public class SingleThreadConsumer
	{
		public event ReceiveMessage ReceiveMessage;


		private IProvider provider;
		private IMessageSession session;
		private Thread receivingThread;

		private ILog log = LogManager.GetLogger(typeof(SingleThreadConsumer));

		public IProvider Provider
		{
			set { provider = value; }
		}

		/// <summary>
		/// to be used for test only
		/// </summary>
		public Thread ReceivingThread
		{
			get { return receivingThread; }
		}

		public void Init()
		{
			session = provider.GetSession();
			receivingThread = new Thread(new ThreadStart(this.ThreadStart));
			receivingThread.IsBackground = true;
			receivingThread.Start();
		}

		public void ThreadStart()
		{
			while(Thread.CurrentThread.IsAlive)
			{
				try
				{
					IMessage message = session.Receive();
					ReceiveMessage(new MessageEventArgs(message));
				}
				catch (Exception e)
				{
					log.Warn("Error processing a received message", e);
				}
			}
		}
	}
}
